<!-- views/procurement/components/SupplierEvaluation.vue -->
<template>
  <el-card class="evaluation-management-card" shadow="never">
    <template #header>
      <div class="card-header">
        <span>供应商评估</span>
        <el-button type="primary" @click="showCreateDialog">新增评估</el-button>
      </div>
    </template>
    
    <!-- 筛选条件 -->
    <el-form :model="filterParams" :inline="true" class="filter-form">
      <el-form-item label="供应商">
        <el-select v-model="filterParams.supplierId" placeholder="请选择供应商" clearable class="form-item-width">
          <el-option
            v-for="supplier in suppliers"
            :key="supplier.id"
            :label="supplier.name"
            :value="supplier.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="filterParams.status" placeholder="请选择状态" clearable class="form-item-width">
          <el-option label="草稿" value="draft" />
          <el-option label="已提交" value="submitted" />
          <el-option label="已审核" value="approved" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="loadEvaluations">查询</el-button>
        <el-button @click="resetFilter">重置</el-button>
      </el-form-item>
    </el-form>
    
    <!-- 评估列表 -->
    <AdvancedTable
      :data="evaluations"
      :columns="evaluationColumns"
      :loading="loading"
      :pagination="paginationConfig"
      row-key="id"
      show-toolbar
      show-refresh
      show-pagination
      @refresh="loadEvaluations"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
      <template #overallScore="{ row }">
        <el-rate
          :model-value="Number(row.overallScore)"
          :max="5"
          disabled
          allow-half
        />
        <span style="margin-left: 10px;">{{ row.overallScore }}分</span>
      </template>
      
      <template #status="{ row }">
        <el-tag v-if="row.status === 'draft'">草稿</el-tag>
        <el-tag v-else-if="row.status === 'submitted'" type="warning">已提交</el-tag>
        <el-tag v-else type="success">已审核</el-tag>
      </template>
      
      <template #actions="{ row }">
        <el-button size="small" @click="viewEvaluation(row)">查看</el-button>
        <el-button size="small" @click="editEvaluation(row)">编辑</el-button>
        <el-button size="small" type="danger" @click="deleteEvaluation(row)">删除</el-button>
      </template>
    </AdvancedTable>
  </el-card>
  
  <!-- 评估对话框 -->
  <el-dialog
    v-model="dialogVisible"
    :title="editingEvaluation ? '编辑评估' : '新增评估'"
    width="600px"
  >
    <el-form
      :model="evaluationForm"
      :rules="evaluationRules"
      ref="evaluationFormRef"
      label-width="100px"
    >
      <el-form-item label="供应商" prop="supplierId">
        <el-select v-model="evaluationForm.supplierId" placeholder="请选择供应商" class="form-item-width">
          <el-option
            v-for="supplier in suppliers"
            :key="supplier.id"
            :label="supplier.name"
            :value="supplier.id"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="评估人" prop="evaluator">
        <el-input v-model="evaluationForm.evaluator" placeholder="请输入评估人" />
      </el-form-item>
      
      <el-form-item label="评估周期" prop="evaluationPeriod">
        <el-input v-model="evaluationForm.evaluationPeriod" placeholder="如: 2025年Q1" />
      </el-form-item>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="质量评分" prop="qualityScore">
            <el-rate
              v-model="evaluationForm.qualityScore"
              :max="5"
              allow-half
            />
            <span style="margin-left: 10px;">{{ evaluationForm.qualityScore }}分</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="交货评分" prop="deliveryScore">
            <el-rate
              v-model="evaluationForm.deliveryScore"
              :max="5"
              allow-half
            />
            <span style="margin-left: 10px;">{{ evaluationForm.deliveryScore }}分</span>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="服务评分" prop="serviceScore">
            <el-rate
              v-model="evaluationForm.serviceScore"
              :max="5"
              allow-half
            />
            <span style="margin-left: 10px;">{{ evaluationForm.serviceScore }}分</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="价格评分" prop="priceScore">
            <el-rate
              v-model="evaluationForm.priceScore"
              :max="5"
              allow-half
            />
            <span style="margin-left: 10px;">{{ evaluationForm.priceScore }}分</span>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="综合评分">
        <el-rate
          v-model="overallScore"
          :max="5"
          disabled
          allow-half
        />
        <span style="margin-left: 10px;">{{ overallScore }}分</span>
      </el-form-item>
      
      <el-form-item label="状态" prop="status">
        <el-select v-model="evaluationForm.status" placeholder="请选择状态" class="form-item-width">
          <el-option label="草稿" value="draft" />
          <el-option label="已提交" value="submitted" />
          <el-option label="已审核" value="approved" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="evaluationForm.remark"
          type="textarea"
          placeholder="请输入备注"
          :rows="3"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="saveEvaluation" :loading="saving">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from '@vue/runtime-core'
import { ElMessage, ElMessageBox } from 'element-plus'
import AdvancedTable from '@/components/AdvancedTable.vue'
import * as evaluationAPI from '@/api/evaluation'
import * as procurementAPI from '@/api/procurement'

interface SupplierEvaluation {
  id: number
  supplierId: number
  evaluator: string
  evaluationDate: string
  qualityScore: number
  deliveryScore: number
  serviceScore: number
  priceScore: number
  overallScore: number
  evaluationPeriod: string
  status: 'draft' | 'submitted' | 'approved'
  remark: string
  createdAt: string
  updatedAt: string
  supplier?: {
    id: number
    name: string
  }
}

interface Supplier {
  id: number
  name: string
}

// 数据状态
const evaluations = ref<SupplierEvaluation[]>([])
const suppliers = ref<Supplier[]>([])
const loading = ref(false)
const saving = ref(false)
const dialogVisible = ref(false)
const editingEvaluation = ref<SupplierEvaluation | null>(null)

// 分页配置
const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

// 筛选参数
const filterParams = reactive({
  supplierId: undefined as number | undefined,
  status: undefined as string | undefined
})

// 评估表单
const evaluationForm = reactive({
  supplierId: undefined as number | undefined,
  evaluator: '',
  evaluationPeriod: '',
  qualityScore: 0,
  deliveryScore: 0,
  serviceScore: 0,
  priceScore: 0,
  status: 'draft' as 'draft' | 'submitted' | 'approved',
  remark: '',
  evaluationDate: ''
})

// 计算综合评分
const overallScore = computed(() => {
  const quality = evaluationForm.qualityScore || 0
  const delivery = evaluationForm.deliveryScore || 0
  const service = evaluationForm.serviceScore || 0
  const price = evaluationForm.priceScore || 0
  return ((quality + delivery + service + price) / 4).toFixed(2)
})

// 监听评分变化，更新综合评分
watch([() => evaluationForm.qualityScore, () => evaluationForm.deliveryScore, 
       () => evaluationForm.serviceScore, () => evaluationForm.priceScore], () => {
  // 综合评分会自动更新
})

// 表单验证规则
const evaluationRules = {
  supplierId: [
    { required: true, message: '请选择供应商', trigger: 'change' }
  ],
  evaluator: [
    { required: true, message: '请输入评估人', trigger: 'blur' }
  ],
  qualityScore: [
    { required: true, message: '请评分', trigger: 'change' }
  ],
  deliveryScore: [
    { required: true, message: '请评分', trigger: 'change' }
  ],
  serviceScore: [
    { required: true, message: '请评分', trigger: 'change' }
  ],
  priceScore: [
    { required: true, message: '请评分', trigger: 'change' }
  ]
}

// 表格列配置
const evaluationColumns = computed(() => [
  {
    prop: 'supplier.name',
    label: '供应商',
    width: 150,
    fixed: 'left'
  },
  {
    prop: 'evaluator',
    label: '评估人',
    width: 100
  },
  {
    prop: 'evaluationPeriod',
    label: '评估周期',
    width: 120
  },
  {
    prop: 'qualityScore',
    label: '质量评分',
    width: 100,
    formatter: (value: number) => `${value}分`
  },
  {
    prop: 'deliveryScore',
    label: '交货评分',
    width: 100,
    formatter: (value: number) => `${value}分`
  },
  {
    prop: 'serviceScore',
    label: '服务评分',
    width: 100,
    formatter: (value: number) => `${value}分`
  },
  {
    prop: 'priceScore',
    label: '价格评分',
    width: 100,
    formatter: (value: number) => `${value}分`
  },
  {
    prop: 'overallScore',
    label: '综合评分',
    width: 150,
    slot: 'overallScore'
  },
  {
    prop: 'status',
    label: '状态',
    width: 100,
    slot: 'status'
  },
  {
    prop: 'evaluationDate',
    label: '评估日期',
    width: 120,
    formatter: (value: string) => value ? value.split('T')[0] : ''
  },
  {
    prop: 'actions',
    label: '操作',
    width: 150,
    fixed: 'right',
    slot: 'actions'
  }
])

// 分页配置
const paginationConfig = computed(() => ({
  currentPage: pagination.page,
  pageSize: pagination.limit,
  total: pagination.total,
  pageSizes: [10, 20, 50, 100],
  layout: 'total, sizes, prev, pager, next, jumper'
}))

// 加载评估列表
const loadEvaluations = async () => {
  loading.value = true
  try {
    const params = {
      ...filterParams,
      page: pagination.page,
      limit: pagination.limit
    }
    
    const response = await evaluationAPI.getEvaluations(params)
    evaluations.value = response.data.list
    pagination.total = response.data.pagination.total
  } catch (error) {
    ElMessage.error('加载评估列表失败: ' + (error as Error).message)
  } finally {
    loading.value = false
  }
}

// 加载供应商列表
const loadSuppliers = async () => {
  try {
    const response = await procurementAPI.getSuppliers({
      page: 1,
      limit: 1000
    })
    suppliers.value = response.data.list
  } catch (error) {
    ElMessage.error('加载供应商列表失败: ' + (error as Error).message)
  }
}

// 显示创建对话框
const showCreateDialog = () => {
  editingEvaluation.value = null
  Object.assign(evaluationForm, {
    supplierId: undefined,
    evaluator: '',
    evaluationPeriod: '',
    qualityScore: 0,
    deliveryScore: 0,
    serviceScore: 0,
    priceScore: 0,
    status: 'draft',
    remark: ''
  })
  dialogVisible.value = true
}

// 查看评估
const viewEvaluation = (evaluation: SupplierEvaluation) => {
  ElMessage.info('查看评估功能待实现')
}

// 编辑评估
const editEvaluation = (evaluation: SupplierEvaluation) => {
  editingEvaluation.value = evaluation
  Object.assign(evaluationForm, { ...evaluation })
  dialogVisible.value = true
}

// 删除评估
const deleteEvaluation = async (evaluation: SupplierEvaluation) => {
  try {
    await ElMessageBox.confirm(`确定要删除对 "${evaluation.supplier?.name}" 的评估吗？`, '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await evaluationAPI.deleteEvaluation(evaluation.id)
    ElMessage.success('评估删除成功')
    loadEvaluations()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除评估失败: ' + (error as Error).message)
    }
  }
}

// 保存评估
const saveEvaluation = async () => {
  saving.value = true
  try {
    // 确保supplierId存在
    if (!evaluationForm.supplierId) {
      ElMessage.error('请选择供应商')
      saving.value = false
      return
    }
    
    // 添加综合评分到表单
    const formData = {
      ...evaluationForm,
      supplierId: evaluationForm.supplierId,
      overallScore: parseFloat(overallScore.value),
      evaluationDate: new Date().toISOString()
    }
    
    if (editingEvaluation.value) {
      // 更新评估
      await evaluationAPI.updateEvaluation(editingEvaluation.value.id, formData)
      ElMessage.success('评估更新成功')
    } else {
      // 创建评估
      await evaluationAPI.createEvaluation(formData)
      ElMessage.success('评估创建成功')
    }
    
    dialogVisible.value = false
    loadEvaluations()
  } catch (error) {
    ElMessage.error('保存评估失败: ' + (error as Error).message)
  } finally {
    saving.value = false
  }
}

// 重置筛选条件
const resetFilter = () => {
  Object.assign(filterParams, {
    supplierId: undefined,
    status: undefined
  })
  loadEvaluations()
}

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  pagination.limit = size
  loadEvaluations()
}

// 处理当前页变化
const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadEvaluations()
}

// 生命周期
onMounted(() => {
  loadEvaluations()
  loadSuppliers()
})
</script>

<style scoped>
.evaluation-management-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-form {
  margin-bottom: 20px;
}

.filter-form .el-form-item {
  margin-right: 20px;
}

.form-item-width {
  width: 200px;
}

</style>